-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
109 lines (97 loc) · 3.14 KB
/
Solution.java
File metadata and controls
109 lines (97 loc) · 3.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import java.util.LinkedList;
import java.util.Scanner;
class HashMap {
static class Node {
int key, value;
Node(int key, int value) {
this.key = key;
this.value = value;
}
}
private static final int TABLE_SIZE = 10;
private LinkedList<Node>[] table;
@SuppressWarnings("unchecked")
public HashMap() {
table = new LinkedList[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++) {
table[i] = new LinkedList<>();
}
}
private int hashFunction(int key) {
return key % TABLE_SIZE;
}
public void insert(int key, int value) {
int index = hashFunction(key);
for (Node node : table[index]) {
if (node.key == key) {
node.value = value; // Update value if key exists
return;
}
}
table[index].add(new Node(key, value));
}
public Integer get(int key) {
int index = hashFunction(key);
for (Node node : table[index]) {
if (node.key == key) {
return node.value;
}
}
return null; // Key not found
}
public void delete(int key) {
int index = hashFunction(key);
table[index].removeIf(node -> node.key == key);
}
public void printHashMap() {
for (int i = 0; i < TABLE_SIZE; i++) {
System.out.print("Index " + i + ": ");
for (Node node : table[i]) {
System.out.print("(" + node.key + " -> " + node.value + ") ");
}
System.out.println();
}
}
}
public class HashMapDemo {
public static void main(String[] args) {
HashMap map = new HashMap();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\n1. Insert\n2. Get\n3. Delete\n4. Print\n5. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter key and value: ");
int key = scanner.nextInt();
int value = scanner.nextInt();
map.insert(key, value);
break;
case 2:
System.out.print("Enter key: ");
key = scanner.nextInt();
Integer result = map.get(key);
if (result == null) {
System.out.println("Key not found.");
} else {
System.out.println("Value: " + result);
}
break;
case 3:
System.out.print("Enter key to delete: ");
key = scanner.nextInt();
map.delete(key);
break;
case 4:
map.printHashMap();
break;
case 5:
scanner.close();
System.exit(0);
default:
System.out.println("Invalid choice.");
}
}
}
}